/**
 * 撤销/重做功能模块
 * 负责初始化编辑器的撤销、重做、格式刷和清除格式等基础操作功能按钮
 */

/**
 * 初始化撤销/重做功能模块
 * @param editor 编辑器实例
 * @param isApple 是否为苹果设备
 */
export default function initUndoRedo(editor: any, isApple: boolean): void {
  // 初始化撤销按钮
  const undoDom = document.querySelector<HTMLDivElement>('.menu-item__undo')!
  undoDom.title = `撤销(${isApple ? '⌘' : 'Ctrl'}+Z)`
  undoDom.onclick = function () {
    console.log('undo')
    editor.command.executeUndo()
  }

  // 初始化重做按钮
  const redoDom = document.querySelector<HTMLDivElement>('.menu-item__redo')!
  redoDom.title = `重做(${isApple ? '⌘' : 'Ctrl'}+Y)`
  redoDom.onclick = function () {
    console.log('redo')
    editor.command.executeRedo()
  }

  // 初始化格式刷按钮
  const painterDom = document.querySelector<HTMLDivElement>(
    '.menu-item__painter'
  )!

  let isFirstClick = true
  let painterTimeout: number
  painterDom.onclick = function () {
    if (isFirstClick) {
      isFirstClick = false
      painterTimeout = window.setTimeout(() => {
        console.log('painter-click')
        isFirstClick = true
        editor.command.executePainter({
          isDblclick: false
        })
      }, 200)
    } else {
      window.clearTimeout(painterTimeout)
    }
  }

  painterDom.ondblclick = function () {
    console.log('painter-dblclick')
    isFirstClick = true
    window.clearTimeout(painterTimeout)
    editor.command.executePainter({
      isDblclick: true
    })
  }

  // 初始化清除格式按钮
  const formatDom =
    document.querySelector<HTMLDivElement>('.menu-item__format')!
  formatDom.onclick = function () {
    console.log('format')
    editor.command.executeFormat()
  }
}
